<template>
  <div
    class="allcard"
    ref="allCard"
    @contextmenu.prevent="
      handleContextMenu({
        e: $event,
        setOptions: setNormalOptions,
      })
    "
  >
    <SiteCard
      v-for="item in urls"
      :key="item.id"
      :data="item"
      @contextmenu.prevent.stop="
        handleContextMenu({
          e: $event,
          setOptions: setItemOptions,
          item,
        })
      "
    />
  </div>

  <n-dropdown
    placement="bottom-start"
    trigger="manual"
    :x="xRef"
    :y="yRef"
    :options="options"
    :show="showDropdown"
    @clickoutside="showDropdown = false"
    @select="showDropdown = false"
  />
  <CardEditor :data="editData"></CardEditor>
</template>
<script setup lang="ts">
import { nextTick, onMounted, onUnmounted, ref, watch } from 'vue'
import Sortable from 'sortablejs/modular/sortable.core.esm.js'
import CardEditor from './CardEditor.vue'
import { useSites } from '@/stores/sites'
import { isMobile } from '@/utils'
import { useDialog, useMessage, type DropdownOption } from 'naive-ui'

const props = defineProps<{
  urls: any[]
  inAll: boolean
}>()

const sitesStore = useSites()
const allCard = ref()
let sortable: {
  option: (arg0: string, arg1: boolean) => void
  destroy: () => void
  options: { disabled: any }
}
onMounted(() => {
  sortable = Sortable.create(allCard.value, {
    onEnd(e: any) {
      const urls = [...props.urls]
      const { newIndex, oldIndex } = e
      if (newIndex == oldIndex) {
        return
      }
      const item = urls[oldIndex]
      urls.splice(oldIndex, 1)
      urls.splice(newIndex, 0, item)
      sitesStore.setSites(urls)
    },
  })
  sortable?.option('disabled', isMobile)
})
onUnmounted(() => {
  sortable?.destroy()
})
watch(
  () => props.inAll,
  () => {
    sortable?.option('disabled', true)
  },
)

const message = useMessage()
const dialog = useDialog()

const options = ref<DropdownOption[]>([])
const setNormalOptions = () => {
  options.value = [
    {
      label: '新增',
      key: 'new',
      props: {
        onClick() {
          editCard({})
        },
      },
    },
    {
      label: '拖动开关',
      key: 'drag',
      props: {
        onClick() {
          if (!props.inAll) {
            message.error('目前只能在全部中拖动排序')
            return
          }
          const disabled = !sortable.options.disabled
          sortable?.option('disabled', disabled)
          message.success(disabled ? '已关闭拖动排序' : '已开启拖动排序')
        },
      },
    },
  ]
}
const setItemOptions = (data: any) => {
  options.value = [
    {
      label: '编辑',
      key: 'edit',
      props: {
        onClick: () => {
          editCard(data)
        },
      },
    },
    {
      label: '删除',
      key: 'delete',
      props: {
        onClick: () => {
          dialog.warning({
            title: '警告',
            content: '确认删除？',
            positiveText: '删除',
            negativeText: '算了',
            onPositiveClick: () => {
              const urls = [...sitesStore.sites]
              const index = urls.findIndex((item: any) => item.id === data.id)
              urls.splice(index, 1)
              return sitesStore.setSites(urls)
            },
          })
        },
      },
    },
  ]
}

const showDropdown = ref(false)
const xRef = ref(0)
const yRef = ref(0)
function handleContextMenu(opt: { e: MouseEvent; setOptions: any; item?: any }) {
  opt.setOptions(opt.item)
  showDropdown.value = false
  nextTick().then(() => {
    showDropdown.value = true
    xRef.value = opt.e.clientX
    yRef.value = opt.e.clientY
  })
}

const editData = ref()
const editCard = (e: any) => {
  editData.value = JSON.parse(JSON.stringify(e))
}
</script>
<style lang="scss">
.allcard {
  display: grid;
  grid-template-columns: repeat(auto-fill, 190px);
  justify-content: center;
  gap: 8px;
}
</style>
